<template>
  <view class="container">
    <view class="detail">
      <form catchsubmit="formSubmit">
        <view v-if="isOrder">
          <view class="pay-status" :style="{color:payStatusFm(detailData.payStatus, true)}">
            {{ payStatusFm(detailData.payStatus) }}
          </view>
          <view class="amount-style edit" v-if="showEdit">
            <text class="label">￥</text>
            <input ref="inputRef" :value="amount" placeholder-class="placeholder-style" data-type='amount'
              @input="inputChange" :focus="isfocus" @blur="editBlurFn" name="amount" placeholder="请输入订单金额" />
          </view>
          <view class="amount-style" v-else>
            <text>￥</text>
            <block v-if="mchntCd===envMchntCd">
              <text class="amount-text">{{ amount ||'--'}}</text>
              <image @click="showEditFn" class="amount-edit-btn" :src="$getImg('fenxiaoyi/edit_btn.png')"></image>
            </block>
            <text v-else>{{ detailData.amount ||'--'}}</text>
          </view>
          <view class="order-date-time">
            订单时间：{{detailData.orderDateTime||'--'}}
          </view>
          <view class="detail-line">
            <view class="detail-line-item"></view>
          </view>
          <view class="item">
            <text class="label">商户名称</text>
            <text class="value">{{detailData.mchntCnAbbr||'--'}}</text>
          </view>
          <view class="item">
            <text class="label">订单日期</text>
            <text class="value">{{detailData.orderDateTime||'--'}}</text>
          </view>
          <view class="item">
            <text class="label">经销商名称</text>
            <text class="value">{{detailData.pharmacyName||'--'}}</text>
          </view>
          <view class="item">
            <text class="label">业务员</text>
            <text class="value">{{detailData.staffName||'--'}}</text>
          </view>
          <view class="item">
            <text class="label">订单备注</text>
            <text class="value">{{detailData.orderBak||'--'}}</text>
          </view>
          <view class="item">
            <text class="label">经销商备注</text>
            <input class="value" :value="payerBak" placeholder-class="placeholder-style" @input="inputChange"
              data-type='payerBak' maxlength="20" name="payerBak" placeholder="请输入经销商备注" />
          </view>
          <block v-if="customBak">
            <view class="item" v-for="(item,index) in customBak" :key="index">
              <text class="label">{{item[0]}}</text>
              <text class="value">{{item[1]}}</text>
            </view>
          </block>
        </view>
        <view v-else>
          <view class="amount-style edit" v-if="showEdit">
            <text class="label">￥</text>
            <input ref="inputRef" :value="amount" placeholder-class="placeholder-style" data-type='amount'
              @input="inputChange" :focus="isfocus" @blur="editBlurFn" name="amount" placeholder="请输入订单金额" />
          </view>
          <view class="amount-style" v-else>
            <text>￥</text>
            <text class="amount-text">{{ amount ||'--'}}</text>
            <image @click="showEditFn" class="amount-edit-btn" :src="$getImg('fenxiaoyi/edit_btn.png')"></image>
          </view>
          <view class="detail-line">
            <view class="detail-line-item"></view>
          </view>
          <view class="item">
            <text class="label">商户名称</text>
            <text class="value">{{addData.mchntCnAbbr||'--'}}</text>
          </view>
          <view class="item">
            <text class="label">经销商名称</text>
            <text class="value">{{addData.pharmacyName||'--'}}</text>
          </view>
          <view class="item">
            <text class="label">业务员</text>
            <text class="value">{{addData.staffName||'--'}}</text>
          </view>
          <view class="item">
            <text class="label">经销商备注</text>
            <input class="value" @input="inputChange" maxlength="20" placeholder-class="placeholder-style"
              name="payerBak" data-type='payerBak' placeholder="请输入经销商备注" />
          </view>
        </view>
      </form>
    </view>
    <view class="btns">
      <block v-if="isOrder">
        <block v-if="payLimit==='2'">
          <button :loading="loading" :disabled="disabled" class="button-pay" @click="pay">去支付</button>
        </block>
        <block v-if="payLimit==='1'">
          <button :loading="loading" :disabled="disabled" class="button-pay" v-if="detailData.flag"
            @click="pay">去支付</button>
          <button v-else :loading="loading" :disabled="disabled" open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber" class="button-pay">去支付</button>
        </block>
      </block>
      <block v-else>
        <block v-if="payLimit==='2'">
          <button :loading="loading" :disabled="disabled" class="button-pay" @click="addOrder">去支付</button>
        </block>
        <block v-if="payLimit==='1'">
          <button :loading="loading" :disabled="disabled" class="button-pay" v-if="flag" @click="addOrder">去支付</button>
          <button v-else :loading="loading" :disabled="disabled" open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber" class="button-pay">去支付</button>
        </block>
      </block>
    </view>
  </view>
</template>

<script>
  import {
    orderDetail,
    getUserPhonePay,
    payOut,
    pharmacyDetail,
    insertPharmacyOrder,
    kangMinModify
  } from "./api/index.js";
  export default {
    data() {
      return {
        detailData: {
          amount: '',
          openId: '',
          orderId: '',
          pharmacyId: '',
          salesId: '',
          mchntCnAbbr: '',
          flag: true,
          customBak: [],
        },
        payLimit: '',
        flag: true,
        addData: {
          pharmacyId: '',
          pharmacyName: '',
          principalName: '',
          address: '',
          telphone: '',
          bak: '',
          mchntCnAbbr: '',
          staffName: '',
          salesId: '',
          orderSource: '2',
        },
        amount: '',
        payerBak: '',
        customBak: [],
        disabled: true,
        loading: false,
        showEdit: false,
        isfocus: false,
        isOrder: true,
        mchntCd: '313010272100002', //特殊给该商户做的需求
        envMchntCd: '332050559120001'
      }
    },
    onLoad(options) {
      uni.hideHomeButton() // 隐藏首页home按钮
      this.getEnvVersion()
      // scene需要使用decodeURIComponent才能获取到生成二维码时传入的orderId
      // 获取二维码传入的参数 确定是店铺码还是订单码 orderId是订单码
      const str = this.getQueryValue(decodeURIComponent(options.q), 'orderId')
      const str1 = this.getQueryValue(decodeURIComponent(options.q), 'pharmacyId')
      if (str1) {
        this.detailData.pharmacyId = str1
        this.detailData.salesId = this.getQueryValue(decodeURIComponent(options.q), 'salesId')
        this.isOrder = false
        this.initPharmacyOrder()
      } else {
        this.detailData.orderId = str
        this.isOrder = true
        this.initOrder()
      }
    },
    methods: {
      showEditFn() {
        this.showEdit = true
        this.isfocus = true
      },
      editBlurFn() {
        this.showEdit = false
      },
      getEnvVersion() {
        try {
          const info = uni.getAccountInfoSync();
          // 区分生产和测试环境特殊商户号
          const env = info.miniProgram.envVersion
          this.envMchntCd = (env === 'develop' || env === 'trial') ? '313010272100002' : '332050559120001'
        } catch (e) {
          this.$toast(e)
        }
      },
      getQueryValue(query, queryName) {
        if (!query.includes(queryName)) return false
        if (query === 'undefined') return false
        var regExp = new RegExp('^.*[?&]' + queryName + '=([^&=?]*)&?.*$', '');
        var parameter = query.replace(regExp, '$1');
        return parameter;
      },
      // 扫订单码进来的查询订单信息
      async initOrder() {
        const _this = this
        uni.login({
          "provider": "weixin",
          "onlyAuthorize": true, // 微信登录仅请求授权认证
          success: async res => {
            try {
              _this.disabled = true
              _this.loading = true
              const resObj = await orderDetail({
                code: res.code,
                orderId: _this.detailData.orderId
              })
              // resObj.customBak = JSON.parse(resObj.customBak)
              _this.detailData = resObj
              _this.payerBak = resObj.payerBak
              if (resObj.mchntCd === this.mchntCd) {
                this.amount = resObj.amount
              } else {
                this.mchntCd = resObj.mchntCd
              }
              if (resObj.customBak) {
                let arr = resObj.customBak.split('</br>').slice(0, -1)
                let list = []
                arr.forEach((item) => {
                  list.push(item.split('：'))
                });
                this.customBak = list
              }
              _this.payLimit = resObj.payLimit
              _this.disabled = false
              _this.loading = false
            } catch (error) {
              _this.disabled = true
              _this.loading = false
              _this.$toast(error.msg || error)
            }
          }
        })
      },
      // 扫店铺码进来的 查询店铺信息
      initPharmacyOrder() {
        const _this = this
        uni.login({
          "provider": "weixin",
          "onlyAuthorize": true, // 微信登录仅请求授权认证
          success: async res => {
            try {
              _this.disabled = true
              _this.loading = true
              const resObj = await pharmacyDetail({
                code: res.code,
                pharmacyId: _this.detailData.pharmacyId,
                salesId: _this.detailData.salesId
              })
              let obj = JSON.parse(JSON.stringify(_this.addData))
              Object.keys(obj).forEach(key => {
                if (key !== 'orderSource') {
                  obj[key] = resObj[key] || ''
                }
              });
              _this.addData = obj
              _this.flag = resObj.flag
              _this.payLimit = resObj.payLimit
              _this.disabled = false
              _this.loading = false
            } catch (error) {
              _this.disabled = true
              _this.loading = false
              _this.$toast(error.msg || error)
            }
          }
        })
      },
      //跳转结果页面
      toSuccess(data) {
        const _this = this
        uni.navigateTo({
          url: '/pages/fenXiaoYi/payResult',
          success: function(res) {
            // 通过eventChannel向被打开页面传送数据
            res.eventChannel.emit('acceptDataFromOpenerPage', {
              data: data,
              orderDetail: _this.detailData
            })
          }
        })
      },
      inputChange: function(e) {
        var cardData = e.target.dataset.type
        this[cardData] = e.target.value
      },
      // 扫店铺码的情况下新增订单
      addOrder(e) {
        if (!this.isOrder) {
          const rule = this.rules()
          if (rule) return this.$toast(rule)
        }
        const _this = this
        uni.login({
          "provider": "weixin",
          "onlyAuthorize": true, // 微信登录仅请求授权认证
          success: async res => {
            try {
              _this.disabled = true
              _this.loading = true
              const params = JSON.parse(JSON.stringify(_this.addData))
              params.code = res.code
              params.amount = _this.amount
              const insertRes = await insertPharmacyOrder(params)
              _this.detailData.orderId = insertRes.orderId
              _this.initOrderAndPay(e)
            } catch (error) {
              _this.disabled = true
              _this.loading = false
              _this.$toast(error.msg || error)
            }
          }
        })
      },
      async initOrderAndPay(e) {
        const _this = this
        uni.login({
          "provider": "weixin",
          "onlyAuthorize": true, // 微信登录仅请求授权认证
          success: async res => {
            try {
              const resObj = await orderDetail({
                code: res.code,
                orderId: _this.detailData.orderId
              })
              resObj.customBak = JSON.parse(resObj.customBak)
              _this.detailData = resObj
              if (resObj.customBak) {
                let arr = resObj.customBak.split('</br>').slice(0, -1)
                let list = []
                arr.forEach((item) => {
                  list.push(item.split('：'))
                });
                _this.customBak = list
              }
              // 如果绑定过手机号或者不需要验证手机号 直接支付 否则获取手机号再支付
              if (_this.flag || resObj.payLimit === '2') {
                _this.pay()
              } else {
                _this.getTel(e)
              }
            } catch (error) {
              _this.disabled = true
              _this.loading = false
              _this.$toast(error.msg || error)
            }
          }
        })
      },
      rules() {
        const reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/
        let str = ''
        if (!reg.test(this.amount)) str = '缴费金额格式错误'
        if (Number(this.amount) > 50000) str = '限制金额为50000'
        if (Number(this.amount) <= 0) str = '限制金额须大于0'
        return str
      },
      async getTel(e) {
        try {
          const _this = this
          //后端解密手机号传过来
          await getUserPhonePay({
            orderId: _this.detailData.orderId,
            openId: _this.detailData.openId || '',
            code: e.detail.code
          })
          //去支付
          _this.pay()
        } catch (error) {
          this.disabled = false
          this.loading = false
          this.$toast(error.msg || error)
        }
      },
      // 通知后台向微信下订单且成功后拉起支付
      pay() {
        if (this.amount) {
          let reg = /^(0(?:\.[0-9]{1,2})?|[1-9]\d{0,8}(?:\.[0-9]{1,2})?)$/
          if (!reg.test(this.amount)) {
            this.$toast('请输入正确的金额！')
            return
          };
        }
        this.disabled = true
        this.loading = true
        if (this.isOrder) {
          this.mchntCd === this.envMchntCd && this.detailData.amount && this.detailData.amount !==
            this.amount ? this.editAmount() : this.payOutAmount()
        } else {
          this.payOutAmount()
        }
      },
      async editAmount() {
        try {
          // const rule = this.rules()
          // if (rule) {
          //   this.setData({ disabled: false, loading: false })
          //   return wx.showToast({ title: rule, icon: "none" });
          // }
          await kangMinModify({
            orderId: this.detailData.orderId,
            amount: this.amount
          })
          this.payOutAmount()
        } catch (error) {
          this.disabled = false
          this.loading = false
          this.$toast(error.msg || error)
        }
      },
      // 通知后台向微信下订单且成功后拉起支付
      payOutAmount() {
        const _this = this
        uni.login({
          "provider": "weixin",
          "onlyAuthorize": true, // 微信登录仅请求授权认证
          success: async res => {
            try {
              const resData = await payOut({
                payChannel: '1',
                payerBak: _this.payerBak,
                code: res.code,
                orderId: _this.detailData.orderId
              })
              // 拉起支付
              uni.requestPayment({
                provider: 'wxpay',
                timeStamp: resData.timeStamp,
                nonceStr: resData.nonceStr,
                package: resData.packageData,
                signType: "RSA",
                paySign: resData.paySign,
                success: function(res) {
                  _this.toSuccess(resData)
                  _this.disabled = false
                  _this.loading = false
                },
                fail: function(res) {
                  _this.disabled = false
                  _this.loading = false
                  if (_this.isOrder) _this.initOrder()
                  _this.$toast(res.msg || res);
                },
              })
            } catch (error) {
              _this.disabled = false
              _this.loading = false
              _this.$toast(error.msg || error)
            }
          },
        })
      },
      // 获取手机号
      async getPhoneNumber(e) {
        try {
          if (!this.isOrder) {
            const rule = this.rules()
            if (rule) return this.$toast(rule)
          }
          this.disabled = true
          this.loading = true
          const _this = this
          //没有获取手机号直接退出
          if (!e.detail.code) {
            _this.disabled = false
            _this.loading = false
            return
          }
          if (_this.isOrder) {
            //如果是扫订单码进来的直接获取手机号然后支付
            _this.getTel(e)
          } else {
            //如果是扫店铺码进来的 要先新建订单然后重新查询该订单然后获取手机号支付
            _this.addOrder(e)
          }
        } catch (error) {
          this.$toast(error.msg)
          this.disabled = false
          this.loading = false
        }
      },
      payStatusFm(val, flag) {
        switch (val) {
          case '':
            return flag ? '#dadadb' : '全部';
          case '01':
            return flag ? '#ff7515' : '待支付';
          case '02':
            return flag ? '#2bcd79' : '交易成功';
          case '03':
            return flag ? '#ff3333' : '交易失败';
          case '04':
            return flag ? '#ff3333' : '已退款';
          case '05':
            return flag ? '#ff3333' : '部分退款';
          case '06':
            return flag ? '#ff3333' : '交易撤销';
          default:
            return flag ? '#333' : '--';
        }
      }
    }
  }
</script>

<style lang="scss">
  /**app.wxss**/
  .container {
    display: flex;
    flex-direction: column;
    align-items: center;
    box-sizing: border-box;
    background-color: #f5f5f5;
    min-height: 100vh;
    padding: 20rpx;
  }

  .content {
    width: 100%;
  }

  .detail {
    padding: 20rpx 0rpx;
    width: 100%;
    background-color: #fff;
    border-radius: 16rpx;
  }

  .detail-line {
    position: relative;
    height: 32rpx;
    background-color: #fff;
    padding: 0 40rpx;
  }

  .detail-line::before,
  .detail-line::after {
    content: "";
    position: absolute;
    top: 0;
    left: -16rpx;
    width: 32rpx;
    height: 32rpx;
    background-color: #f5f5f5;
    border-radius: 50%;
  }

  .detail-line::after {
    right: -16rpx;
    left: unset;
  }

  .detail-line-item {
    height: 16rpx;
    border-bottom: 1rpx dashed #eee;
  }

  .pay-status {
    text-align: center;
    font-size: 36rpx;
  }

  .order-date-time {
    text-align: center;
    color: #999999;
    font-size: 30rpx;
  }

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 20rpx;
    padding: 10rpx 0;
    border-bottom: 1rpx solid #eee;
  }

  .item:nth-last-child(1) {
    border-bottom: 0;
  }

  .item input {
    height: 76rpx;
    line-height: 76rpx;
  }

  .label {
    min-width: 240rpx;
    line-height: 76rpx;
    font-size: 32rpx;
    color: #333333;
    font-family: PingFang SC;
    align-items: center;
  }

  .value {
    flex: 1;
    word-break: break-word;
    font-size: 32rpx;
    color: #666;
  }

  .btns {
    width: 100%;
    display: flex;
  }

  .button-pay {
    height: 96rpx;
    background-color: #ff7515;
    margin: 40rpx 0 80rpx;
    flex: 1;
    border-radius: 48rpx;
    color: #fff;
    font-weight: 400;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40rpx;
  }

  .amount-style {
    font-size: 72rpx;
    margin: 20rpx 0;
    padding: 0 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    color: #333333;
  }

  .amount-style .amount-text {
    max-width: 400rpx;
    word-break: break-all;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .amount-style .label {
    font-size: 72rpx;
  }

  .amount-style.edit {
    margin: 20rpx 140rpx;
    border-bottom: 1rpx solid #eee;
    padding: 0;
  }

  .amount-style.edit input {
    height: 96rpx;
    width: 300rpx;
  }

  .amount-style.edit .label {
    margin-right: 20rpx;
    min-width: 0;
  }

  .amount-edit-btn {
    width: 36rpx;
    height: 36rpx;
    margin-left: 20rpx;
  }

  .placeholder-style {
    color: rgb(204, 204, 204);
    font-size: 32rpx;
  }
</style>